package com.shengdong.water.code.adapter

import android.animation.ObjectAnimator
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.core.view.marginLeft
import androidx.databinding.ViewDataBinding
import com.shengdong.water.R
import com.shengdong.water.code.base.BaseRecyclerAdapter
import com.shengdong.water.code.bean.NodeType
import com.shengdong.water.code.bean.TreeNode
import com.shengdong.water.code.bean.VIEW_TYPE_PARENT
import com.shengdong.water.code.bean.VIEW_TYPE_VIDEO
import com.shengdong.water.databinding.ItemTreeParentBinding
import com.shengdong.water.databinding.ItemTreeVideoBinding

class VideoTreeAdapter : BaseRecyclerAdapter<TreeNode, ViewDataBinding>() { // VB 设为通用的 ViewDataBinding

    // getLayoutId() 在多视图类型下不再直接使用，而是通过 getItemViewType 和 onCreateViewHolder 控制
    override fun getLayoutId() = R.layout.item_tree_parent // 或者一个占位布局，实际会在 onCreateViewHolder 覆盖


    override fun getItemViewType(position: Int) =  getItem(position).viewType // TreeNode 中增加了 viewType 字段


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<ViewDataBinding> {
        val inflater = LayoutInflater.from(parent.context)
        val binding: ViewDataBinding = when (viewType) {
            VIEW_TYPE_PARENT -> {
                // 假设你的 item_tree_parent.xml 使用了 DataBinding
                 ItemTreeParentBinding.inflate(inflater, parent, false)
                // 如果没有为特定布局生成 Binding 类，可以使用 DataBindingUtil
//                androidx.databinding.DataBindingUtil.inflate(inflater, R.layout.item_tree_parent, parent, false)
            }
            VIEW_TYPE_VIDEO -> {
                 ItemTreeVideoBinding.inflate(inflater, parent, false)
//                androidx.databinding.DataBindingUtil.inflate(inflater, R.layout.item_tree_video, parent, false)
            }
            else -> throw IllegalArgumentException("Invalid view type")
        }
        return BaseViewHolder(binding)
    }

    override fun bindData(binding: ViewDataBinding, item: TreeNode, position: Int) {
        super.bindData(binding, item, position)
        // 在 BaseRecyclerAdapter 的 onBindViewHolder 中会调用这个方法
        // 你需要根据 binding 的实际类型来操作视图
        when (item.viewType) {
            VIEW_TYPE_PARENT -> {
                val parentBinding = binding as ItemTreeParentBinding
                parentBinding.item = item
                val arrowImageView = parentBinding.itemParentArrow
                val root = parentBinding.rootView
                // --- 动画逻辑 ---
                val rotation  = if (item.isExpanded) 90f else 0f // 向下箭头认为是90度，向右是0度
                if (arrowImageView.rotation != rotation ) {
                    ObjectAnimator.ofFloat(arrowImageView, "rotation", arrowImageView.rotation, rotation).apply {
                        duration = 200 // 动画时长，单位毫秒
                        interpolator = AccelerateDecelerateInterpolator() // 插值器，使动画看起来更自然
                        start()
                    }
                } else {
                    // 如果角度已经正确，确保图标也正确（防止动画未执行完就被重绑）
                    arrowImageView.rotation = rotation  // 立即设置到目标角度
                }
                arrowImageView.setImageResource(R.mipmap.ic_arrow_right)
                parentBinding.executePendingBindings()
            }
            VIEW_TYPE_VIDEO -> {
                val videoBinding = binding as ItemTreeVideoBinding
                videoBinding.item = item
                videoBinding.executePendingBindings()
            }
        }
    }

    // --- 树形列表核心逻辑 ---

    // 初始加载或完全刷新时，使用此方法更新数据
    fun setTreeData(rootNodes: List<TreeNode>) {
        val flatNodes = mutableListOf<TreeNode>()
        generateFlatList(rootNodes, 0, flatNodes, true) // 初始时，根据 isExpanded 状态决定是否添加子节点
        setItems(flatNodes) // setItems 是 BaseRecyclerAdapter 的方法
    }

    // 点击父节点时调用此方法
    fun toggleNodeExpansion(parentNode: TreeNode) {
        if (parentNode.type != NodeType.PARENT || parentNode.children.isNullOrEmpty()) {
            return
        }

        val currentItems = getItems().toMutableList() // 获取当前列表的副本
        val parentPosition = currentItems.indexOf(parentNode)
        if (parentPosition == -1) return

        parentNode.isExpanded = !parentNode.isExpanded
        notifyItemChanged(parentPosition) // 更新父节点图标

        if (parentNode.isExpanded) {
            // 展开：将子节点添加到列表的正确位置
            val childrenToInsert = mutableListOf<TreeNode>()
            generateFlatList(parentNode.children, parentNode.level + 1, childrenToInsert, true) // 递归添加

            if (childrenToInsert.isNotEmpty()) {
                currentItems.addAll(parentPosition + 1, childrenToInsert)
                // 更新 BaseRecyclerAdapter 的数据源并通知
                setItems(currentItems) // 或者更精细的 notifyItemRangeInserted
                }
        } else {
            // 折叠：从列表中移除所有直接和间接子节点
            val childrenToRemoveCount = removeAllDescendants(parentNode, currentItems, parentPosition + 1)
            if (childrenToRemoveCount > 0) {
                // 更新 BaseRecyclerAdapter 的数据源并通知
                setItems(currentItems) // 或者更精细的 notifyItemRangeRemoved
               recursivelySetExpandedFalse(parentNode.children)
            }
        }
    }

    private fun recursivelySetExpandedFalse(nodes: List<TreeNode>?) {
        nodes?.forEach { node ->
            node.isExpanded = false
            if (node.type == NodeType.PARENT) {
                recursivelySetExpandedFalse(node.children)
            }
        }
    }

    // 递归生成扁平化列表
    private fun generateFlatList(
        nodes: List<TreeNode>?,
        level: Int,
        targetList: MutableList<TreeNode>,
        includeChildrenOfExpanded: Boolean
    ) {
        nodes?.forEach { node ->
            node.level = level
            node.viewType = if (node.type == NodeType.PARENT) VIEW_TYPE_PARENT else VIEW_TYPE_VIDEO
            targetList.add(node)
            if (includeChildrenOfExpanded && node.isExpanded && node.type == NodeType.PARENT && !node.children.isNullOrEmpty()) {
                generateFlatList(node.children, level + 1, targetList, true)
            }
        }
    }

    // 递归移除所有后代节点，并返回移除的数量
    private fun removeAllDescendants(
        parentNode: TreeNode,
        currentList: MutableList<TreeNode>,
        startIndexInList: Int
    ): Int {
        var removedCount = 0
        val iterator = currentList.listIterator(startIndexInList)
        while (iterator.hasNext()) {
            val currentNode = iterator.next()
            // 如果当前节点的层级小于或等于父节点，说明已经不是其后代了
            if (currentNode.level <= parentNode.level) {
                break
            }
            iterator.remove()
            removedCount++
        }
        return removedCount
    }


    // 你可能需要重写 BaseRecyclerAdapter 的 areItemsTheSame 和 areContentsTheSame
    // 以确保 DiffUtil 能正确工作，特别是对于树形结构的变化。
    override fun areItemsTheSame(oldItem: TreeNode, newItem: TreeNode): Boolean {
        return oldItem.label == newItem.label // 使用唯一 ID 判断
    }

    override fun areContentsTheSame(oldItem: TreeNode, newItem: TreeNode): Boolean {
        // 判断内容是否相同，需要考虑 name, isExpanded, level 等，或者更简单地：
        return oldItem == newItem // 如果 TreeNode 是 data class 并且你希望比较所有属性
    }
}